package site.isscloud.jt809;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

public class GPSData {
    private int longitude;
    private int latitude;
    private short speed;
    private short direction;
    private long time;

    public GPSData(int longitude, int latitude, short speed, short direction, long time) {
        this.longitude = longitude;
        this.latitude = latitude;
        this.speed = speed;
        this.direction = direction;
        this.time = time;
    }

    public int getLongitude() {
        return longitude;
    }

    public void setLongitude(int longitude) {
        this.longitude = longitude;
    }

    public int getLatitude() {
        return latitude;
    }

    public void setLatitude(int latitude) {
        this.latitude = latitude;
    }

    public short getSpeed() {
        return speed;
    }

    public void setSpeed(short speed) {
        this.speed = speed;
    }

    public short getDirection() {
        return direction;
    }

    public void setDirection(short direction) {
        this.direction = direction;
    }

    public long getTime() {
        return time;
    }

    public void setTime(long time) {
        this.time = time;
    }

    public static GPSData fromByteArray(byte[] bytes) {
        ByteBuffer buffer = ByteBuffer.wrap(bytes).order(ByteOrder.BIG_ENDIAN);
        int longitude = buffer.getInt();
        int latitude = buffer.getInt();
        short speed = buffer.getShort();
        short direction = buffer.getShort();
        byte[] timeBytes = new byte[6];
        buffer.get(timeBytes);
        String timeStr = new String(timeBytes, StandardCharsets.UTF_8);
        // Parse 6-character date string (YYMMDD) and convert to timestamp
        LocalDateTime dateTime = LocalDateTime.parse(timeStr + "000000", DateTimeFormatter.ofPattern("yyMMddHHmmss"));
        long time = dateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
        return new GPSData(longitude, latitude, speed, direction, time);
    }

    public byte[] toByteArray() {
        ByteBuffer buffer = ByteBuffer.allocate(28).order(ByteOrder.BIG_ENDIAN);
        buffer.putInt(longitude);
        buffer.putInt(latitude);
        buffer.putShort(speed);
        buffer.putShort(direction);
        String timeStr = LocalDateTime.ofInstant(Instant.ofEpochMilli(time), ZoneId.systemDefault()).format(DateTimeFormatter.ofPattern("yyMMddHHmmss"));
        byte[] timeBytes = timeStr.getBytes(StandardCharsets.UTF_8);
        buffer.put(timeBytes);
        return buffer.array();
    }
}
